"""
Case Type   :
Case Name   : 使用多线程向表中插入uuid函数;查看表中数据是否会重复
Create At   : 2024/07/25
Owner       : lvlintao666
Description :
        1.创建表
        2.多线程向表中插入数据
        3.查看表中数据是否重复
        4.清理环境;删除表
Expect      :
        1.创建表成功
        2.插入数据成功
        3.表中数据没有重复
        4.删除成功
History     :
"""
import os
import unittest

from yat.test import Node

from testcase.utils.ComThread import ComThread
from testcase.utils.CommonSH import CommonSH
from testcase.utils.CommonSQL import CommonSQL
from testcase.utils.Constant import Constant
from testcase.utils.Logger import Logger


class UuidNotRepeat(unittest.TestCase):

    def setUp(self):
        self.log = Logger()
        self.log.info(f'----{os.path.basename(__file__)} start----')
        self.constant = Constant()
        self.test_node = Node('PrimaryDbUser')
        self.comSh = CommonSH('PrimaryDbUser')
        self.table_name = 't_uuid_0024'

    def test_uuid_not_repeat(self):
        text = '------step1:创建表;expect:成功------'
        self.log.info(text)
        create_cmd = f'drop table if exists {self.table_name};' \
                     f'create table {self.table_name}(id text);'
        self.log.info(create_cmd)
        create_msg = self.comSh.execut_db_sql(create_cmd)
        self.log.info(create_msg)
        self.assertEquals(self.constant.CREATE_TABLE_SUCCESS,
                          create_msg, '执行失败' + text)

        text = '------step2 多线程向表中插入数据;expect:成功------'
        self.log.info(text)
        insert_cmd = f'insert into {self.table_name} values(uuid());'
        for _ in range(200):
            insert_thread = ComThread(self.comSh.execut_db_sql,
                                      args=(insert_cmd,))
            insert_thread.setDaemon(True)
            insert_thread.start()
            insert_thread.join(20)

        text = '------step3:查询表中是否有重复的值;expect:成功------'
        self.log.info(text)
        select_cmd = f'select count(id),id from {self.table_name} group by ' \
                     f'id having count(id)>1;'
        self.log.info(select_cmd)
        select_msg = self.comSh.execut_db_sql(select_cmd)
        self.log.info(select_msg)
        self.assertTrue('0 row' in select_msg.splitlines()[-1], '执行失败' + text)

    def tearDown(self):
        text = '------step4:清理环境;expect:成功------'
        self.log.info(text)
        drop_cmd = f'drop table {self.table_name};'
        self.log.info(drop_cmd)
        drop_msg = self.comSh.execut_db_sql(drop_cmd)
        self.log.info(drop_msg)
        self.assertIn(self.constant.DROP_TABLE_SUCCESS, drop_msg,
                      '执行失败' + text)
        self.log.info(f'----{os.path.basename(__file__)} end----')
